package com.zhangxun.controller;

import com.zhangxun.domain.SysMenu;
import com.zhangxun.service.SysMenuService;
import com.zhangxun.util.SecurityUtil;
import com.zhangxun.vo.MenuAndAuthVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "菜单管理接口")
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;

    @GetMapping("/nav")
    @ApiOperation(value = "查询菜单和用户权限")
    @PreAuthorize("hasAuthority('sys:menu:info')")
    public ResponseEntity<MenuAndAuthVo> selectMenuAndAuth(){

        //通过安全上下文对象(封装成了工具类)获取用户名，这里对用户获取用户名的方法进行了重写，实际上是返回的用户的id。
        Long userId = SecurityUtil.getUserId();
        List<SimpleGrantedAuthority> authorities = SecurityUtil.getAuthorities();
        List<String> collect = authorities.stream().map(auth -> auth.getAuthority()).collect(Collectors.toList());
        //通过userId关联查询到菜单
        List<SysMenu> list =  sysMenuService.selectMenuByUserId(userId);
        //对菜单进行层级封装
        List<SysMenu> menuList = treeList(list,0l);
        MenuAndAuthVo menuAndAuthVo = new MenuAndAuthVo();
        menuAndAuthVo.setMenuList(menuList);
        menuAndAuthVo.setAuthorities(collect);
        return ResponseEntity.ok(menuAndAuthVo);
    }

    /**
     * 层级封装的方法
     * @param list 集合当中保存的菜单
     * @param parentId 封装的第一层菜单的id
     * @return
     */
    private List<SysMenu> treeList(List<SysMenu> list, long parentId) {

        List<SysMenu> menuList = list.stream().filter(user->user.getParentId().equals(parentId)).collect(Collectors.toList());

        menuList.stream().forEach(menu->menu.setList(treeList(list,menu.getMenuId())));

        return menuList;
    }

    @GetMapping("/table")
    @ApiOperation("查询菜单")
    @PreAuthorize("hasAuthority('sys:menu:info')")
    public ResponseEntity<List<SysMenu>> table(){

        return ResponseEntity.ok(sysMenuService.listWithRedis());
    }


}
